package com.jeomo.mem.starter.service.impl;

import com.jeomo.mem.starter.sysoption.SysAdminMailOption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 管理员邮箱服务
 *
 * @author:Jackpot
 * @create 2021-01-21 17:07
 * @description:
 */
@Service
public class AdminMailService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private JavaMailSender mailSender;
    @Autowired(required = false)
    private SysAdminMailOption sysAdminMailOption;


    @Value("${spring.mail.username}")  //发送人的邮箱
    private String from;

    @Async
    public void sendMail(String title, String content, String toEmail) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from); // 发送人的邮箱
        message.setSubject(title); //标题
        message.setTo(toEmail); //发给谁  对方邮箱
        message.setText(content); //内容
        mailSender.send(message);
    }

    @Async
    public void sendMailToAdmin(String title, String content) {

        String message = "管理员邮箱配置为空,请检查!";
        sysAdminMailOption.load();
        List<String> adminMails = sysAdminMailOption.getAdminMails();
        if (adminMails==null || adminMails.isEmpty()) {
            logger.info(message);
            return;
        }
        for (String adminMail : adminMails) {
            sendMail(title,content,adminMail);
        }
    }
}
